package top.wangjiu.reactive.rpc.decode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;
import top.wangjiu.reactive.rpc.model.RpcRequest;

import java.util.List;

public class RpcRequestDecoder extends ByteToMessageDecoder {


    private static RuntimeSchema<RpcRequest> schema = RuntimeSchema.createFrom(RpcRequest.class);
    private int length = 0;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if(length == 0 && in.readableBytes()>=4){
            length = in.readInt();
        }
        if(in.readableBytes()>=length && length >0){
            byte[] data = new byte[length];
            in.readBytes(data);
            RpcRequest request = schema.newMessage();
            ProtostuffIOUtil.mergeFrom(data, request, schema);
            out.add(request);
            length = 0;
        }

    }
}
